package TCP;

import java.io.*;
import java.net.Socket;

/**
 * @author Cheng-02
 * @version V1.0
 * @Package test
 * @date 2024/4/10 上午10:05
 */
public class Day10_Server_Thread_outclass extends Thread {
    private  Socket socket;
    public Day10_Server_Thread_outclass(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            while (true) {
                String line = reader.readLine();
                if (line == null) {
                    break;
                }
                System.out.println(socket.getRemoteSocketAddress() + "说：" + line);
                //广播
                for (Socket s : Day10_Server_Thread.onLineSockets) {
                    if (s == socket) {
                        continue;
                    }
                    OutputStream outputStream = s.getOutputStream();
                    DataOutputStream dos = new DataOutputStream(outputStream);
                    PrintWriter pw = new PrintWriter(dos, true);
                    pw.println(socket.getRemoteSocketAddress() + "说：" + line);
                }
            }
        } catch (IOException e) {
            System.out.println(socket.getRemoteSocketAddress() + "下线了");
            Day10_Server_Thread.onLineSockets.remove(socket);
            throw new RuntimeException(e);
        }
    }
}
